﻿#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>


void logLevelBufC(int a_priority, char *data, int len,const  char *pre_str, int printlen);

void logLevelC(int level, const char *fmt, ...)
{
    (void)level;
    char        buf[1024] = {0};
    va_list        args;

    va_start(args,fmt);
    vsnprintf(buf,1024, fmt,args);
    va_end(args);

    fprintf(stdout, "%s\n", buf);
}

void logInfo1(const char *fmt, ...)
{
    char        buf[1024] = {0};
    va_list        args;

    va_start(args,fmt);
    vsnprintf(buf,1024, fmt,args);
    va_end(args);


   // qDebug("%s", buf);
    fprintf(stdout, "%s\n", buf);

}

void logInfoP(const char *fmt, ...)
{
    char        buf[1024] = {0};
    va_list        args;

    va_start(args,fmt);
    vsnprintf(buf,1024, fmt,args);
    va_end(args);

   // qDebug("%s", buf);
    fprintf(stdout, "%s", buf);

}

void logInfoBufC(char *data, int len,const  char *pre_str,int printlen)
{
    logLevelBufC(1, data, len, pre_str, printlen);
}

void logLevelBufC(int a_priority, char *data, int len,const  char *pre_str, int printlen)
{
    (void)a_priority;
    char tmpstr[32];
    char buf1[2048] = {0};
    int maxlen = sizeof(buf1) / sizeof(buf1[0]);
    int curlen;
    int tmplen;

    if (-1 == printlen)
    {
        printlen = len;
    }
    snprintf(buf1,2048, "[%s](%7d):", pre_str, len);
    int i = 0;

    curlen = strlen(buf1);
    if (printlen > len)
    {
        printlen = len;
    }
    for (i = 0; i < printlen; i++)
    {
        sprintf(tmpstr, "%02d ", data[i]);
        if (i % 5 == 0)
        {
           sprintf(tmpstr, "  %02x ", data[i] & 0xff);
        }
        else
        {
            sprintf(tmpstr, "%02x ", data[i] & 0xff);
         }
        tmplen = strlen(tmpstr);
        if (curlen + tmplen < maxlen)
        {
            strncpy(buf1 + curlen,tmpstr, tmplen);
            curlen += tmplen;
        }
    }

    fprintf(stderr, "%s\r\n", buf1);

}



void openfile();
void logFileStr(char *str);
void logFile(const char *fmt, ...);

FILE *outfile = NULL;
void openfile()
{
    outfile = fopen("monitoragvlog.txt", "w");
    if (NULL == outfile)
    {
       // fprintf("void openfile: open file file");
        exit(1);
    }
}
void logFileStr(char *str)
{
    if (nullptr == outfile)
    {
        return;
    }
    fputs(str, outfile);
    fprintf(outfile, "\n");
   fflush(outfile);
}
void logFile(const char *fmt, ...)
{
    if (nullptr == outfile)
    {
        return;
    }

    char        buf[1024] = {0};
    va_list        args;

    va_start(args,fmt);
    vsnprintf(buf,1024, fmt,args);
    va_end(args);

    fprintf(outfile, "%s\n", buf);
    fflush(outfile);
}
